package com.squirrel.michale;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author guanhao 观浩
 * @version 1.0.0.0
 * @createTime 2023/2/2 9:06 PM
 * @company Michale Squirrel
 * @link
 * @description
 */
public class Exam_iLearning20221111 {

    class FlowchartSys {


    Set<Integer> middleNodeSet = new HashSet<>(); // 中继节点set

 

    Set<Integer> nodeSet = new HashSet<>(); // 普通节点set

 

    Map<Integer, List<Integer>> linkMap = new HashMap<>(); // link map

 

    public FlowchartSys() {

 

    }

 

    public boolean addNode(int nodeId, int nodeType) {

        if (middleNodeSet.contains(nodeId) || nodeSet.contains(nodeId)) {

            return false;

        }

        return nodeType == 1 ? middleNodeSet.add(nodeId) : nodeSet.add(nodeId);

    }

 

    public boolean addConnection(int connectId, int startNodeId, int endNodeId) {

        // 开始结束相等，开始没有，结束没有，已有link

        boolean isFail = startNodeId == endNodeId

            || (!middleNodeSet.contains(startNodeId) && !nodeSet.contains(startNodeId))

            || (!middleNodeSet.contains(endNodeId) && !nodeSet.contains(endNodeId)) || linkMap.containsKey(connectId);

        if (isFail) {

            return false;

        }

        List<Integer> linkList = new ArrayList<>();

        linkList.add(startNodeId);

        linkList.add(endNodeId);

        linkMap.put(connectId, linkList);

        return true;

    }

 

    public boolean removeConnection(int connectId) {

        return linkMap.remove(connectId) != null;

    }

 

    public boolean removeNode(int nodeId) {

        linkMap.entrySet().removeIf(entry -> entry.getValue().contains(nodeId));

        if (nodeSet.contains(nodeId)) {

            return nodeSet.remove(nodeId);

        }

        if (middleNodeSet.contains(nodeId)) {

            return middleNodeSet.remove(nodeId);

        }

        return false;

    }

 

    public int[] query(int nodeId) {

        if (!nodeSet.contains(nodeId) && !middleNodeSet.contains(nodeId)) {

            return new int[0];

        }

        // 将所有手动连接中开始是此节点的查出来

        Set<Integer> linkSet = linkMap.values()

            .stream()

            .filter(item -> item.get(0) == nodeId)

            .mapToInt(item -> item.get(1))

            .boxed()

            .collect(Collectors.toSet());

        // 将所有的中继节点加到set中，代表自动创建的

        linkSet.addAll(middleNodeSet);

        // 移除自身

        linkSet.remove(nodeId);

 

        List<Integer> linkList = new ArrayList<>(linkSet);

        Collections.sort(linkList);

        int[] result = new int[linkList.size()];

        for (int i = 0; i < linkList.size(); i++) {

            result[i] = linkList.get(i);

        }

        return result;

    }

}
}
